package com.cjst.controller.api.alarm;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cjst.pojo.base.AlarmResult;
import com.cjst.pojo.part.Parts;
import com.cjst.pojo.sys.FileInfo;
import com.cjst.service.base.AlarmResultService;
import com.cjst.service.part.PartsService;
import com.cjst.service.sys.FileInfoService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.DownloadUtil;
import com.cjst.util.ResultMap;
import com.cjst.util.common.DateUtil;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;
import com.google.gson.JsonObject;

import io.swagger.annotations.Api;

@Controller
@RequestMapping("/api/alarm")
@Api(value = "emsModel", description = "快递查询模块")
public class AlarmController {
	private static Logger log = Logger.getLogger(AlarmController.class);

	@Value("${img.location}")
	private String fileUploadPath;
	@Value("${file.path}")
	private String filePath;
	
	@Autowired
	private AlarmResultService alarmResultService;

	@Autowired
	private PartsService partsService;

	@Autowired
	private FileInfoService fileInfoService;
	
	@Value("${file.path}")
	private String begin_url;
	
	
	private final String[] reportType={"打架斗殴","聚众赌博","吸毒","吸烟","噪音扰民","投诉建议","求助反馈","其他"};
	
	

	@RequestMapping(value = "/getTopAlarm", method = RequestMethod.POST)
	@ResponseBody
	public String getTopAlarm() {

		List<AlarmResult> alarmResults = null;
		List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		try {
			WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
			wherePrams.orderBy(" create_time desc ");

			/**
			 * 限制返回数量 LIMIT
			 * 
			 */
			alarmResults = alarmResultService.list(wherePrams);

			/**
			 * LIMIT次循环，填上设备地址 多表查询？
			 */
			if (alarmResults != null && alarmResults.size() > 0) {
				alarmResults.forEach(tmp -> {

					tmp.setImgUrl(begin_url + tmp.getImgUrl());

					WherePrams partPrams = Method.where("id", C.EQ, tmp.getPartId());
					Parts parts = partsService.get(partPrams);

					ResultMap map = new ResultMap(tmp);

					if (parts != null) {
						map.put("address", parts.getPartAddress());
					} else {
						map.put("address", "");
					}
					result.add(map.getData());
				});
			}

			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}
	
	@RequestMapping(value = "/getTopAlarmByPage", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String getTopAlarmByPage(int page,int size) {
		
		if(size<=0) {
			size=10;
		}
		if(page<1) {
			page=1;
		}	   				

		List<AlarmResult> alarmResults = null;
		List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		try {
			WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
			wherePrams.and("type", C.EQ, 1);
			/**
			 * 限制返回数量 LIMIT
			 * 
			 */
			alarmResults = alarmResultService.listPage(wherePrams," ORDER BY create_time desc limit "+(page-1)*size+","+size);

			/**
			 * LIMIT次循环，填上设备地址 多表查询？
			 */
			if (alarmResults != null && alarmResults.size() > 0) {
				alarmResults.forEach(tmp -> {

					tmp.setImgUrl(begin_url + tmp.getImgUrl());

					WherePrams partPrams = Method.where("id", C.EQ, tmp.getPartId());
					Parts parts = partsService.get(partPrams);

					ResultMap map = new ResultMap(tmp);

					if (parts != null) {
						map.put("address", parts.getPartAddress());
					} else {
						map.put("address", "");
					}
					result.add(map.getData());
				});
			}

			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}

	
	/**
	 * 
	 * @param partId
	 * @param page  要查询的页，1开始
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/getAlarmByPartId", method = RequestMethod.POST)
	@ResponseBody
	public String getAlarmByPartId(String partId,int page,int size) {
		if(size==0||page<1) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "参数异常", null);
			return robj.toString();
		}
		
		WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
		wherePrams.and("partId", C.EQ, partId);

		List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();

		try {
			
	        			
			List<AlarmResult> alarmResults=alarmResultService.listPage(wherePrams, " limit "+(page-1)*size+","+size);
	        

			if (alarmResults != null && alarmResults.size() > 0) {
				alarmResults.forEach(tmp -> {
					tmp.setImgUrl(begin_url + tmp.getImgUrl());

					ResultMap map = appendAddress(tmp);

					result.add(map.getData());

				});
			}
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);

			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}

	/**
	 * 根据警报ID获取详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getAlarmById", method = RequestMethod.POST)
	@ResponseBody
	public String getAlarmById(String id) {
		WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
		wherePrams.and("id", C.EQ, id);

		AlarmResult alarmResult = alarmResultService.get(wherePrams);

		// 获取设备地址
		ResultMap map = appendAddress(alarmResult);

		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", map);

		return obj.toString();
	}

	/**
	 * 获取从createTime开始的警报
	 * 
	 * @param createTime
	 * @return
	 */

	// 未完
	@RequestMapping(value = "/getAlarmByCreateTime", method = RequestMethod.POST)
	@ResponseBody
	public String getAlarmByCreateTime(String createTime) {
		WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
		wherePrams.and("createTime", C.DAEQ, createTime);

		/**
		 * 限制返回数量 LIMIT
		 * 
		 */
		List<AlarmResult> alarmResults = alarmResultService.list(wherePrams);

		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", alarmResults);

		return obj.toString();
	}

	@RequestMapping(value = "/updateIsBroadcastById", method = RequestMethod.POST)
	@ResponseBody
	public String updateIsBroadcastById(String id) {
		int result = 0;
		try {

			WherePrams wherePrams = Method.where("id", C.EQ, id);

			AlarmResult alarmResult = alarmResultService.get(wherePrams);
			alarmResult.setIsBroadcast(1);
			result = alarmResultService.updateLocal(alarmResult);
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}

	/**
	 * 待定 ids格式
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/updateIsBroadcastByIds", method = RequestMethod.POST)
	@ResponseBody
	public String updateIsBroadcastByIds(String ids) {
		int result = 0;
		try {
			// 分隔符待定
			String[] tmp = ids.split(";");

			List<String> params = Arrays.stream(tmp).collect(Collectors.toList());

			WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
			wherePrams.andIn("id", C.IN, params);

			List<AlarmResult> alarmResult = alarmResultService.list(wherePrams);

			alarmResult.forEach(one -> {
				one.setIsBroadcast(1);
				alarmResultService.updateLocal(one);
			});
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", 1);
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}

	/**
	 * 根据公园获取设备警报
	 */
	@RequestMapping(value = "/getAlarmByLocationId")
	@ResponseBody
	public String getAlarmByLocationId(String locationId,int page,int size) {
		if(size==0||page<1) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "参数异常", null);
			return robj.toString();
		}
		
		List<AlarmResult> result = null;
		List<ResultMap> result2 = null;
		try {
			WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
			wherePrams.and("areaId", C.EQ, locationId);

			List<Parts> parts = partsService.listPage(wherePrams," limit "+(page-1)*size+","+size);

			// 获取该地址内的所有设备ID
			List<String> alarmParams = new ArrayList<String>();
			if (parts != null && parts.size() > 0) {
				for (Parts one : parts) {
					alarmParams.add(one.getId());
				}
			}

			// 根据设备找到对应的警报
			WherePrams wherePrams2 = Method.where("delFlag", C.EQ, 0);
			wherePrams2.andIn("partId", C.IN, alarmParams);

			result = alarmResultService.list(wherePrams2);

			if (result != null && result.size() > 0) {
				result.forEach(tmp -> {
					tmp.setImgUrl(begin_url + tmp.getImgUrl());

					// 增加ADDRESS属性
					result2.add(appendAddress(tmp));

				});

			}
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result2);

			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}
	
	@RequestMapping(value = "/getReportType", method = RequestMethod.POST)
	@ResponseBody
	public String getReportType() {
		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", reportType);
		return obj.toString();
	}
	
	
//	@RequestMapping(value = "/report", method = RequestMethod.POST)
//	@ResponseBody
//	public String report(HttpServletRequest request,AlarmResult alarmResult) {
//		if(alarmResult==null) {
//			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "alarmResult==null", null);
//			return robj.toString();
//		}
//		try {
//			Date now=new Date();
//			String dir=DateUtil.dateToString(now, "yyyyMMdd");
//			//需要返回值
//			ArrayList<String> image_result=uploadMultiFile(request,"alarmResult/"+dir);
//			
//			alarmResult.setCreateTime(DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss"));
//			
//			//上报：11
//			alarmResult.setType(11);
//			//需要设置一个TYPE来区分或者统一imgUrl就是数组
//			//alarmResult.setImgUrl(image_result.toString());
//			String result_id = alarmResultService.addLocalByid(alarmResult);
//			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result_id);
//			
//			
//			
//			StringBuffer params=new StringBuffer();
//			
//			for(int i=0;i<image_result.size();i++) {
//				if(i!=image_result.size()-1) {
//					params.append("'"+image_result.get(i)+"'"+",");
//				}
//				else {
//					params.append("'"+image_result.get(i)+"'");
//				}
//			}
//			
//			//.excuse("update t_part_img set is_del=1 where is_del=0 and type='" + imgType + "'"+" and relation_no= '" + relationNo + "'");
//			fileInfoService.excuse("update t_file set foreign_id='"+result_id+"' where id in("+params.toString()+")");
//			
//
//			return obj.toString();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			log.error(e);
//			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
//			return robj.toString();
//		}
//	}
	
	
	
	
	
	//content
	//img
	
	@RequestMapping(value = "/reportContent", method = RequestMethod.POST)
	@ResponseBody
	public String reportContent(AlarmResult alarmResult) {
		if(alarmResult==null) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "alarmResult==null", null);
			return robj.toString();
		}
		try {
			Date now=new Date();
			
			alarmResult.setCreateTime(DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss"));
			alarmResult.setType(11);
			//上报：11
			//alarmResult.setAlarmType(alarmType);
			//需要设置一个TYPE来区分或者统一imgUrl就是数组
			//alarmResult.setImgUrl(image_result.toString());
			String result_id = alarmResultService.addLocalByid(alarmResult);
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result_id);
			
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return obj.toString();
		}
	}
	
	
	@RequestMapping(value = "/reportFiles", method = RequestMethod.POST)
	@ResponseBody
	public String reportFiles(MultipartFile[] files,String id) {
		if(files==null||files.length==0) {
			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		
		
		try {
			Date now=new Date();
			String dir=DateUtil.dateToString(now, "yyyyMMdd");
			//需要返回值
			ArrayList<String> image_result=uploadMultiFile(files,"alarmResult/"+dir);
			
			StringBuffer params=new StringBuffer();
			
			for(int i=0;i<image_result.size();i++) {
				if(i!=image_result.size()-1) {
					params.append("'"+image_result.get(i)+"'"+",");
				}
				else {
					params.append("'"+image_result.get(i)+"'");
				}
			}
			
			//.excuse("update t_part_img set is_del=1 where is_del=0 and type='" + imgType + "'"+" and relation_no= '" + relationNo + "'");
			fileInfoService.excuse("update t_file set foreign_id='"+id+"' where id in("+params.toString()+")");
			
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}
	}
	
	
	@RequestMapping(value = "/reportImgs", method = RequestMethod.POST)
	@ResponseBody
	public String reportImgs(MultipartFile[] files,String id) {
		if(files==null||files.length==0) {
			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		
		
		try {
			Date now=new Date();
			String dir=DateUtil.dateToString(now, "yyyyMMdd");
			//需要返回值
			ArrayList<String> image_result=uploadMultiFile(files,"alarmResult/"+dir);
			
			StringBuffer params=new StringBuffer();
			
			for(int i=0;i<image_result.size();i++) {
				if(i!=image_result.size()-1) {
					params.append("'"+image_result.get(i)+"'"+",");
				}
				else {
					params.append("'"+image_result.get(i)+"'");
				}
			}
			
			//.excuse("update t_part_img set is_del=1 where is_del=0 and type='" + imgType + "'"+" and relation_no= '" + relationNo + "'");
			fileInfoService.excuse("update t_file set foreign_id='"+id+"' where id in("+params.toString()+")");
			
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}
	}
	
	
	@RequestMapping(value = "/reportVedios", method = RequestMethod.POST)
	@ResponseBody
	public String reportVedios(MultipartFile[] files,String id) {
		if(files==null||files.length==0) {
			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		
		
		try {
			Date now=new Date();
			String dir=DateUtil.dateToString(now, "yyyyMMdd");
			//需要返回值
			ArrayList<String> image_result=uploadMultiFile(files,"alarmResult/"+dir);
			
			StringBuffer params=new StringBuffer();
			
			for(int i=0;i<image_result.size();i++) {
				if(i!=image_result.size()-1) {
					params.append("'"+image_result.get(i)+"'"+",");
				}
				else {
					params.append("'"+image_result.get(i)+"'");
				}
			}
			
			//.excuse("update t_part_img set is_del=1 where is_del=0 and type='" + imgType + "'"+" and relation_no= '" + relationNo + "'");
			fileInfoService.excuse("update t_file set foreign_id='"+id+"' where id in("+params.toString()+")");
			
			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
			return obj.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}
	}
	
//	@RequestMapping(value = "/reportFiles", method = RequestMethod.POST)
//	@ResponseBody
//	@Transactional
//	public String reportFiles(String imgs,String vedio,String id) {
//		
//		if(id==null||"".equals(id)) {
//			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
//			return obj.toString();
//		}
//		if(imgs==null&&vedio==null) {
//			ResultObj obj = new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
//			return obj.toString();
//		}
//		
//		
//		System.out.println("imgs:"+imgs);
//		System.out.println("vedio:"+vedio);
//		
//		try {
//			Date now = new Date();
//			String dir = DateUtil.dateToString(now, "yyyyMMdd");
//
//			ArrayList<String> files_result = new ArrayList<String>();
//			if (imgs != null) {
//				String[] multiImgs = imgs.split(",");
//
//				// 需要返回值
//
//				for (int i = 0; i < multiImgs.length; i++) {
//					files_result.add(downloadSingleFile(multiImgs[i], dir));
//				}
//				fileInfoService.excuse("update t_file set type='" + 21 + "' where id in(" + files_result.toString().trim().replace("[", "'").replace("]", "'").replace(",", "','") + ")");
//			}
//			//单个视频文件！！！！！
//			if (vedio != null&&"".equals(vedio)) {
//				String file_id=downloadSingleFile(vedio, dir);
//				files_result.add(file_id);
//				fileInfoService.excuse("update t_file set type='" + 22 + "' where id ='" + file_id + "'");
//			}
//
//			StringBuffer params = new StringBuffer();
//			for (int i = 0; i < files_result.size(); i++) {
//				if (i != files_result.size() - 1) {
//					params.append("'" + files_result.get(i) + "'" + ",");
//				} else {
//					params.append("'" + files_result.get(i) + "'");
//				}
//			}
//
//			// .excuse("update t_part_img set is_del=1 where is_del=0 and type='" + imgType
//			// + "'"+" and relation_no= '" + relationNo + "'");
//			fileInfoService.excuse("update t_file set foreign_id='" + id + "' where id in(" + params.toString() + ")");
//
//			ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
//			return obj.toString();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			log.error(e);
//			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
//			return robj.toString();
//		}
//	}
	
	
	@RequestMapping(value = "/reportFile", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String reportFile(MultipartFile file,String id,String type) {
		
		if(id==null||id.length()<5) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "id exception", null);
			return robj.toString();
		}
		
		Date now=new Date();
		String dir=DateUtil.dateToString(now, "yyyyMMdd");
		String fileId=uploadSingleFile(file,"alarmResult/"+dir);
		
		fileInfoService.excuse("update t_file set foreign_id='" + id + "' , type='"+type+"' where id ='" + fileId + "'");
		
		Map<String,String> data=new HashMap<String,String>();
		data.put("id", fileId);
		data.put("filePath", filePath + "/alarmResult/"+dir+"/"+fileId);
		
		
		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",data);
		return obj.toString();
	}
	
	
	
	
	
	@RequestMapping(value = "/getReports", method = RequestMethod.POST)
	@ResponseBody
	public String getReports() {
	
		WherePrams wherePrams=Method.where("delFlag", C.EQ,0 );
		wherePrams.and("type", C.EQ, 11);
		
		List<AlarmResult> alarmResult=alarmResultService.list(wherePrams);
		
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", alarmResult);
		return robj.toString();
	}
	
	@RequestMapping(value = "/getReportDetailById", method = RequestMethod.POST)
	@ResponseBody
	public String getReportDetailById(String id) {
		
		if(id==null||id.length()<5) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "id exception", null);
			return robj.toString();
		}
		
		WherePrams wherePrams=Method.where("delFlag", C.EQ,0 );
		wherePrams.and("id", C.EQ, id);
		
		AlarmResult alarmResult=alarmResultService.get(wherePrams);
		
		
		WherePrams wherePrams2=Method.where("foreignId", C.EQ,alarmResult.getId());
		List<FileInfo> files=fileInfoService.list(wherePrams2);
		
		
		List<String> file_urls=new ArrayList<String>();
		files.forEach(tmp->{
			//图片
			if(tmp.getType()==21) {
				file_urls.add(filePath +tmp.getUrl());
			}
			//视频
			if(tmp.getType()==22) {
				alarmResult.setVedioUrl(filePath +tmp.getUrl());
			}
			
		});
		
		alarmResult.setImgUrlArray(file_urls);
		
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", alarmResult);
		return robj.toString();
	}
	
	
	@RequestMapping(value = "/getReportsByCreator", method = RequestMethod.POST)
	@ResponseBody
	public String getReportsByCreator(String id) {
		WherePrams wherePrams = Method.where("delFlag", C.EQ, 0);
		wherePrams.and("type", C.EQ, 11);
		if(id==null||id.length()<5) {
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "id exception", null);
			return robj.toString();
		}
		wherePrams.and("createBy", C.EQ, id);

		List<AlarmResult> alarmResult = alarmResultService.listPage(wherePrams," ORDER BY create_time desc ");
		
		alarmResult.forEach(tmp->{
			WherePrams tmpPrams=Method.where("foreignId", C.EQ, tmp.getId());
			tmpPrams.and("type", C.EQ, 21);
			List<FileInfo> files=fileInfoService.list(tmpPrams);
			
			ArrayList<String> imgs=new ArrayList<String>();
			if(files!=null&&files.size()!=0) {
				files.forEach(f->{
					imgs.add(filePath +f.getUrl());
				});
			}
			tmp.setImgUrlArray(imgs);
		});

		
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", alarmResult);
		return robj.toString();
	}
	
	
	
//	@RequestMapping(value="/",method=RequestMethod.POST)
//	@ResponseBody
//	public String updateAlarmResultStatus(String id,String resultStatus) {
//		
//		
//		
//		AlarmResult alarmResult=alarmResultService.get(arg0);
//		
//		return null;
//	}
//	

	/**
	 * 单个警报
	 * 
	 * @param parts
	 * @param alarmResult
	 */
	public ResultMap appendAddress(AlarmResult alarmResult) {

		// 为了增加部分POJO不足的属性
		ResultMap map = new ResultMap(alarmResult);
		// 获取设备地址
		WherePrams partPrams = Method.where("id", C.EQ, alarmResult.getPartId());
		Parts parts = partsService.get(partPrams);

		if (parts != null) {
			map.put("address", parts.getPartAddress());
		} else {
			map.put("address", "");
		}

		return map;
	}
	
//	
//	/**
//	 * 多个警报
//	 */
//	public List<ResultMap> appendAddress(List<AlarmResult> alarmResults) {
//
//		List<ResultMap> result = new ArrayList<ResultMap>();
//
//		if (alarmResults != null && alarmResults.size() > 0) {
//			alarmResults.forEach(tmp -> {
//				tmp.setImgUrl(begin_url + tmp.getImgUrl());
//
//				WherePrams partPrams = Method.where("id", C.EQ, partId);
//				Parts parts = partsService.get(partPrams);
//				// 为了增加部分POJO不足的属性
//				ResultMap map = new ResultMap(tmp);
//
//				if (parts != null) {
//					map.put("address", parts.getPartAddress());
//				} else {
//					map.put("address", "");
//				}
//				// System.out.println(new
//				// ResultObj(ResultCode.RESULT_SUCCESS,"success",map).toString());
//				result.add(map.getData());
//
//			});
//		}
//	}
	
	
	public ArrayList<String> uploadMultiFile(HttpServletRequest request,String targetDir) {
		
		ArrayList<String> result=new ArrayList<String>();
		
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	        if(fileMap == null || fileMap.size() == 0){
	            return null;
	        }
	        Collection<MultipartFile> files = fileMap.values();
	        for(MultipartFile file:files){
	        	String id=uploadSingleFile(file,targetDir);
	        	result.add(id);
	        }

		return result;
	}
	
	public ArrayList<String> uploadMultiFile(MultipartFile[] files,String targetDir) {
		
		ArrayList<String> result=new ArrayList<String>();
		
		 
	        if(files == null || files.length == 0){
	            return null;
	        }
	        for(MultipartFile file:files){
	        	String id=uploadSingleFile(file,targetDir);
	        	result.add(id);
	        }

		return result;
	}
	
//	public String uploadSingleFiles(MultipartFile[] files, String dirs) {
//		
//	}
	public String uploadSingleFile(MultipartFile file, String dirs) {
		try {

			// 文件上传路径
			String serverPath = fileUploadPath;

			String uploadDir = "";

			// 文件名称
			String fileName = file.getOriginalFilename();
			// 文件后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (dirs != null && dirs.length() > 0) {
				uploadDir = uploadDir + "/" + dirs + "/" + "avator";
			} else {
				uploadDir = uploadDir + "/" + "avator";
			}

			// 检查目录是否存在
			File dir = new File(serverPath + uploadDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 随机名称
			String randomFileName = UUID.randomUUID().toString();
			// 文件存在服务器上的路径
			String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

			// 将文件上传到文集的物理地址
			File serverFile = new File(serverPath + fileUrl);
			file.transferTo(serverFile);
			log.info("文件上传成功");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("fileUrl", fileUrl);
			map.put("filePath", filePath + fileUrl);
			
			
			FileInfo tmp=new FileInfo();
			tmp.setFileName(randomFileName);
			tmp.setUrl(fileUrl);
			
			//视频
			if(suffix.equals("mp4")) {
				tmp.setType(22);
			}
			//图片
			else {
				tmp.setType(21);
			}
			
			
			String id=fileInfoService.addLocalByid(tmp);
			
			return id;

		} catch (Exception e) {
			log.error(e.getMessage());
			return null;
		}

	}
	
	public String downloadSingleFile(String url, String dirs) {
		try {
			System.out.println("开始下载文件url:"+url);
			// 文件上传路径
			String serverPath = fileUploadPath;

			String uploadDir = "";

			// 文件名称
			String fileName = url.substring(url.lastIndexOf("/"));
			//String fileName = url;
			// 文件后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (dirs != null && dirs.length() > 0) {
				uploadDir = uploadDir + "/" + dirs + "/" + "avator";
			} else {
				uploadDir = uploadDir + "/" + "avator";
			}

			// 检查目录是否存在
			File dir = new File(serverPath + uploadDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 随机名称
			String randomFileName = UUID.randomUUID().toString();
			// 文件存在服务器上的路径
			String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

			// 将文件上传到文集的物理地址
			File serverFile = new File(serverPath + fileUrl);
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("fileUrl", fileUrl);
			map.put("filePath", filePath + fileUrl);
			
			
			System.out.println("path:"+filePath + fileUrl);
			URL httpurl = new URL(url);  
	        FileUtils.copyURLToFile(httpurl, serverFile);  
			
	            
			
			FileInfo tmp=new FileInfo();
			tmp.setFileName(randomFileName);
			tmp.setUrl(fileUrl);
			
//			//视频
//			if(suffix.equals("mp4")) {
//				tmp.setType(11);
//			}
//			//图片
//			else {
//				tmp.setType(12);
//			}
			
			
			String id=fileInfoService.addLocalByid(tmp);
			System.out.println("id:"+id);
			return id;

		} catch (Exception e) {
			log.error(e.getMessage());
			return null;
		}

	}
	
	

}
